/**
 * Title AppleLoginService
 * Package com.sba.manage.service.impl
 * Copyright 2024 www.hundsun.com All Rights Reserved.
 *
 * @author gd
 * @date 2024/9/9 10:29 PM
 * @version V5.1.2
 */
package com.ruoyi.manage.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.manage.bean.AppleLoginVO;
import com.ruoyi.manage.service.IAppleLogin;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;

/**
 * AppleLoginService
 * ClassName AppleLoginService
 *
 * @author gd
 * @date 2024/9/9 10:29 PM
 */
@Slf4j
@Service
public class AppleLoginServiceImpl implements IAppleLogin {

    private final static String APPLE_AUTH_URL = "https://appleid.apple.com/auth/keys";

    private final static String ISS = "https://appleid.apple.com";

    @Override
    public boolean verify(AppleLoginVO appleLoginVO) {
        //这里传过来的identityToken应该是三个.分割,解密之后
        String identityToken = appleLoginVO.getIdentityToken();
        try {
            if (identityToken.split("\\.").length > 1) {
                String firstDate = new String(Base64.decodeBase64(identityToken.split("\\.")[0]), StandardCharsets.UTF_8);
                String claim = new String(Base64.decodeBase64(identityToken.split("\\.")[1]), StandardCharsets.UTF_8);
                String kid = JSONObject.parseObject(firstDate).get("kid").toString();
                String aud = JSONObject.parseObject(claim).get("aud").toString();
                String sub = JSONObject.parseObject(claim).get("sub").toString();
                PublicKey publicKey = getPublicKey(kid);
                if (publicKey == null) {
                    log.error("Apple have no info data!");
                    return false;
                }
                boolean reuslt = verify(publicKey, identityToken, aud, sub);
                if (reuslt) {
                    log.info("苹果登录授权成功");
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("苹果登录授权异常", e);
        }
        log.error("identityToken格式不正确");
        return false;
    }

    private PublicKey getPublicKey(String kid) {
        try {
            JSONObject debugInfo = getHttp(APPLE_AUTH_URL);
            JSONObject jsonObject = debugInfo.getJSONObject("body");
            String keys = jsonObject.getString("keys");
            JSONArray jsonArray = JSONObject.parseArray(keys);
            if (jsonArray.isEmpty()) {
                return null;
            }
            for (Object object : jsonArray) {
                JSONObject json = ((JSONObject) object);
                if (json.getString("kid").equals(kid)) {
                    String n = json.getString("n");
                    String e = json.getString("e");
                    BigInteger modulus = new BigInteger(1, Base64.decodeBase64(n));
                    BigInteger publicExponent = new BigInteger(1, Base64.decodeBase64(e));
                    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent);
                    KeyFactory kf = KeyFactory.getInstance("RSA");
                    return kf.generatePublic(spec);
                }
            }
        } catch (Exception e) {
            log.error("getPublicKey异常!", e);
            e.printStackTrace();
        }
        return null;

    }

    private boolean verify(PublicKey key, String jwt, String audience, String subject) {
        boolean result = false;
        JwtParser jwtParser = Jwts.parser().setSigningKey(key);
        jwtParser.requireIssuer(ISS);
        jwtParser.requireAudience(audience);
        jwtParser.requireSubject(subject);
        try {
            Jws<Claims> claim = jwtParser.parseClaimsJws(jwt);
            if (claim != null && claim.getBody().containsKey("auth_time")) {
                return true;
            }
        } catch (ExpiredJwtException e) {
            log.error("getPublicKey异常{苹果identityToken过期}", e);
        } catch (SignatureException e) {
            log.error("getPublicKey异常{苹果identityToken非法}", e);
        }
        return result;
    }

    private JSONObject getHttp(String url) {
        log.info("[请求地址]： " + url);
        JSONObject resultJson = new JSONObject();
        resultJson.put("code", -1);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpPost = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                if (response.getStatusLine().getStatusCode() == 200) {
                    String resp = EntityUtils.toString(entity);
                    resultJson.put("code", 0);
                    resultJson.put("body", JSONObject.parseObject(resp));
                } else {
                    resultJson.put("code", response.getStatusLine().getStatusCode());
                    log.error("[错误码] ：" + response.getStatusLine().getStatusCode());
                    log.error("[请求地址] ：" + url);
                }

            } finally {
                response.close();
            }
        } catch (IOException e) {
            log.error("[异常]", e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error("[httpclient 关闭异常]", e);
            }
        }
        return resultJson;
    }
}